$(function () {
    obj.init();
});

var obj = new function() {
    return {
        applyForm: null,
        form: null,
        targetObj: null,
        otherTr: null,
        checkTeacher: true,
        isDefault: true,
        init: function () {
            this.applyForm = $('#reference_apply_form');
            this.form = new xhForm(this.applyForm);
            this.form.parse();
            this.funObj().addData();//获取select数据
            this.listener();
        },
        listener: function () {
            var $this = this;
            $('#school, #subject').unbind('change').on('change',function () {
                if (modify === 1){
                    $this.funObj().addTeacherData();
                } else {
                    if (modify === 2 && $this.isDefault === false){//修改初始化做请求
                        $this.funObj().addTeacherData();
                    }
                }
            });
            $('#haveId').unbind('change').on('change',function () {
                $this.funObj().bindHaveIdSelect();
            });
            $('#bt_modal_confirm',window.top.document).click(function () {
                $this.funObj().saveData();
            });
            $('#bookName').on('change keyup', function () {
                $this.funObj().addId($('#bookName').val());
            });
            $('#addBookId').click(function () {
                $this.funObj().addBookId();
            });
            //匹配应用
            $('#addApp').click(function () {
                $this.funObj().addApp();
            });
        },
        funObj: function () {
            var form = this.applyForm;
            var $this = this;
            var teaArr = [];
            var id = iId;
            return {
                addData: function () {
                    if (modify === 2){//修改
                        params = {type: modify, id: id};
                    } else {//创建
                        params = {};
                    }
                    // $('#haveId').select2();
                    xhExtra.ajaxRequest('res/getReferAllSelectData', params, {check:true}, function (data) {
                        schoolObj = $('#school').select2({placeholder: '选择学校', data: data.school, allowClear: true});
                        applicationObj = $('#application').select2({placeholder: '选择应用',data: data.app, allowClear: true});
                        classObj = $('#class').select2({placeholder: '选择年级',data: data.class, allowClear: true});
                        subjectObj = $('#subject').select2({placeholder: '选择科目',data: data.subject, allowClear: true});
                        volumeObj = $('#volume').select2();
                        if(modify === 2){//修改
                            schoolObj.val([apply_data.iSchoolId]).trigger('change');
                            applicationObj.val([apply_data.sAppCode]).trigger('change');
                            classObj.val([apply_data.iClassId]).trigger('change');
                            subjectObj.val([apply_data.iSubject]).trigger('change');
                            volumeObj.val([apply_data.iVolumeId]).trigger('change');
                            teacherObj = $('#teacher').select2({placeholder: '选择教师',data: data.allTeaList,allowClear: true,multiple : true});
                            $.each(data.teaList, function (key, value) {
                                teaArr.push(value);
                            });
                            teacherObj.val(teaArr).trigger('change');//填充数据
                            $this.isDefault = false;
                            teaArr = [];
                        }else{//创建
                            var handleData = window.top.xhTop.getActiveFrame().obj.handleData;
                            if (handleData.school !== null){
                                schoolObj.val([handleData.school]).trigger('change');
                            }
                            if (handleData.application !== null){
                                applicationObj.val([handleData.application]).trigger('change');
                            }
                            if (existApp !== 'noApp'){
                                applicationObj.val([existApp]).trigger('change').prop('disabled',true).select2();
                            }
                            if (handleData.class_data !== null){
                                classObj.val([handleData.class_data]).trigger('change');
                            }
                            if (handleData.subject !== null){
                                subjectObj.val([handleData.subject]).trigger('change');
                            }
                            if (handleData.teacher !== null){
                                $this.funObj().addTeacherData(false, handleData.teacher);
                            }
                        }

                    });
                },
                addTeacherData: function (exist, existTeacherObject) {//是否是编辑、是否存在操作的教师数据
                    var schoolId = form.find('#school').val();
                    var subjectId = form.find('#subject').val();
                    $("#teacher").find("option").remove();
                    $this.checkTeacher = true;
                    xhExtra.ajaxRequest('res/getTeacherData', {schoolId:schoolId,subjectId:subjectId}, {check:true}, function (data) {
                        if (data.checkTeacher === false){
                            $this.checkTeacher = false;
                        }
                        teacherObj = $('#teacher').select2({placeholder: '选择教师',data: data.data,allowClear: true,multiple : true});
                        if (exist){//编辑
                            $.each(apply_data.sTeacherList, function (key, value) {
                                teaArr.push(value);
                            });
                            teacherObj.val(teaArr).trigger('change');//填充数据
                        }else{//创建
                            if (existTeacherObject !== null && existTeacherObject !== undefined ){
                                $.each(existTeacherObject, function (key, value) {
                                    teaArr.push(value);
                                });
                                teacherObj.val(teaArr).trigger('change');//填充数据
                            }
                        }
                        teaArr = [];
                    });
                },
                bindHaveIdSelect: function () {
                    var text =form.find('#haveId').val();
                    var str = '';
                    var str_1 = '';
                    if($this.targetObj != null){
                        $this.targetObj.remove();
                    }
                    if($this.otherTr != null){
                        $this.otherTr.remove();
                    }
                    if (modify === 1) {//新建
                        if(text === '2'){//是
                            str = '<tr id = remark_1>' +
                                '<td><label>备注：</label></td><td colspan="5" style="width: 100px;"><textarea style="height:50px" id="remark" name="remark" class="form-control" type="text"></textarea></td>' +
                                '</tr>';
                            $this.targetObj  = $(str);
                            form.find('#isNo_1, #isNo_2, #isNo_3, #isNo_4, #isNo_5, #isNo_6').remove();
                            form.find('table tbody').append($this.targetObj);
                            form.find('#referenceId').attr('disabled', false);
                            form.find("#application").val([]).trigger('change').prop('disabled',true).select2();
                            document.getElementById('addApp').style.display = 'table-cell';
                        }else{//否
                            str_1 =
                                '<tr>' +
                                '<td><label>录入需求：</label></td><td colspan="5" style="width: 200px;"><textarea style="height:50px" id="typeIn" name="typeIn" class="form-control" type="text" placeholder="必填"></textarea></td>' +
                                '</tr>' +
                                '<tr>' +
                                '<td><label>当前进度：</label></td><td colspan="5" style="width: 200px;"><textarea style="height:50px" id="progress" name="progress" class="form-control" type="text" placeholder="当前教学进度，必填"></textarea></td>' +
                                '</tr>' +
                                '<tr>' +
                                '<td><label>教学进度：</label></td><td colspan="5" style="width: 200px;"><textarea style="height:50px" id="teachProgress" name="teachProgress" class="form-control" type="text" placeholder="两周后教学进度，必填"></textarea></td>' +
                                '</tr>' +
                                '<tr>' +
                                '<td ><label>是否纸质：</label></td><td><select id="isPaper" class="form-control" name="isPaper"><option value="1">否</option> <option value="2">是</option></select></td>' +
                                '<td ><label>电子教辅：</label></td><td><select id="electronic" class="form-control" name="electronic"><option value="1">否</option> <option value="2">是</option></select></td>' +
                                '<td ><label>教辅数量：</label></td><td><input id="bookNum" class="form-control" name="bookNum" type="text" autocomplete="off"></td>' +
                                '</tr>'+
                                '<tr><td ><label>购买链接：</label></td><td colspan="5"><input id="buyUrl" class="form-control" name="buyUrl" type="text" placeholder="必填" autocomplete="off"></td></tr>' +
                                '<tr>' +
                                '<td><label>备注：</label></td><td colspan="5" style="width: 100px;"><textarea style="height:50px" id="remark" name="remark" class="form-control" type="text"></textarea></td>' +
                                '</tr>';
                            $this.otherTr = $(str_1);
                            form.find('#remark_1').remove();
                            form.find('table tbody').append($this.otherTr);
                            $('#referenceId').val('');
                            form.find('#referenceId').attr('disabled', true);
                            form.find("#application").prop('disabled',false).select2();
                            document.getElementById('addApp').style.display = 'none';
                            xhExtra.ajaxRequest('res/getAllApp', null, {check:true}, function (data) {
                                applicationObj = $('#application').html('').select2({placeholder: '选择应用',data: data, allowClear: true});
                                var handleData = window.top.xhTop.getActiveFrame().obj.handleData;
                                if (handleData.application !== null){
                                    applicationObj.val([handleData.application]).trigger('change');
                                }
                            });
                        }
                    } else {//修改
                        if(text === '2'){//是
                            document.getElementById('showOrDisplay').style.display = 'none';
                        } else {//否
                            document.getElementById('showOrDisplay').style.display = 'table-cell';
                        }
                    }
                },
                saveData: function () {
                    var school = $('#school').val();
                    var application = $('#application').val();
                    var grade = $('#class').val();
                    var subject = $('#subject').val();
                    var teacher = $('#teacher').val();
                    var bookName = $('#bookName').val();
                    var haveId = $('#haveId').val();
                    var referenceId = $('#referenceId').val();
                    var buyUrl = $('#buyUrl').val();
                    var typeIn = $('#typeIn').val();
                    var progress = $('#progress').val();
                    var teachProgress = $('#teachProgress').val();
                    var iId = id;
                    var url = '';
                    if (modify === 1) {
                        if (school < 1 || application < 1 || grade < 1 || subject < 1 || bookName < 1 || (haveId === '2' && referenceId < 1) || (haveId === '1' && (buyUrl < 1 || typeIn < 1 || progress < 1 || teachProgress < 1))){
                            window.top.xhTop.showError('请填写完整信息');
                            xhExtra.setBtnNormal($('#bt_modal_confirm', window.top.document));
                            return false;
                        }
                    }

                    if ($this.checkTeacher === true){
                        if (teacher < 1 || teacher.length < 1){
                            window.top.xhTop.showError('请选择教师信息');
                            xhExtra.setBtnNormal($('#bt_modal_confirm', window.top.document));
                            return false;
                        }
                    }
                    if (modify === 1){//创建
                        $this.funObj().fillHandleData(school, application, grade, subject, teacher);
                        url = 'res/saveReferenceApply';
                    }else{//修改
                        url = 'res/saveModifyReferApply';
                    }
                    xhExtra.ajaxRequest(url, {iId: iId,school: school, application: application,grade: grade,
                            subject: subject,teacher: teacher,haveId: haveId,referenceId: referenceId,bookName:bookName,remark: $('#remark').val(),isPaper: $('#isPaper').val(),
                            bookNum: $('#bookNum').val(),electronic: $('#electronic').val(),buyUrl: buyUrl,typeIn: typeIn,progress: progress, teachProgress: teachProgress,
                            volume: $('#volume').val()
                        }, {success: true,check:false},function (res) {
                        if(res.code === 200){
                            window.top.xhTop.showSuccess(res.msg);
                            window.top.xhTop.getActiveFrame().obj.dataGrid.reload();
                            window.top.xhTop.closeModal();
                        } else {
                            window.top.xhTop.showError(res.error);
                            xhExtra.setBtnNormal($('#bt_modal_confirm',window.top.document));
                        }
                    });
                },
                fillHandleData: function (school, application, grade, subject, teacher) {
                    handleData = window.top.xhTop.getActiveFrame().obj.handleData;
                    handleData.school = school;
                    handleData.application = application;
                    handleData.class_data = grade;
                    handleData.subject = subject;
                    handleData.teacher = teacher;
                },
                addId: function (key) {
                    if (modify !== 1) {//创建时不匹配id
                        xhExtra.ajaxRequest('res/bookIdsByNameKey', {key: key}, {check:true}, function (data) {
                            $('#bookIdArr').empty().select2({placeholder: '选择书id', data: data, allowClear: true});
                        });
                    }
                },
                addBookId: function () {
                    var selectId = $('#bookIdArr').val();
                    if (selectId && selectId !== '--请选择--') {
                        $('#referenceId').val(selectId);
                    }
                },
                addApp: function () {
                    var bookId = $('#referenceId').val();
                    if (!bookId) {
                        window.top.xhTop.showError('请输入书本id后操作');
                        xhExtra.setBtnNormal($('#bt_modal_confirm', window.top.document));
                        return false;
                    }
                    xhExtra.ajaxRequest('res/getBookAppById', {bookId: bookId}, {check:true}, function (data) {
                        if (data.type === 0) {//存在应用
                            $('#application').prop('disabled',false).empty().select2({placeholder: '请选择', data: data.data});
                        } else if (data.type === 1) {
                            form.find("#application").val([]).trigger('change').prop('disabled',true).select2();
                            window.top.xhTop.showError('该书不允许教辅申请');
                            xhExtra.setBtnNormal($('#bt_modal_confirm', window.top.document));
                            return false;
                        }
                    });
                }
            }
        }
    }
};
